/**
 * @file model.js
 */

"use strict";

const plural = require("plural");
const moment = require("moment");
const env = process.env.mode == "prod"? "production": "development";
const config = require("../../knexfile")[env];
const knex = require("knex")(config);

/**
 * Base model for local storage.
 *
 * @class Model
 */
class Model {
  /**
   * @constructor
   * @param {string} tableName - need to be singular
   * @example
   *  ```
   *  let subject = new Model("pet");
   *  console.log(subject.tableName); // return "pets"
   *  ```
   */
  constructor(tableName) {
    this.tableName = plural(tableName);
  }

  /**
   * Insert new entry in the table.
   *
   * @method store
   * @param {Object} payload - properties of the entry
   * @return {Promise} id inserted if found, rejection if not
   */
  store(payload) {
    if (!(payload)) {
      let message = {
        status: "error",
        message: "Model:store payload wrong"
      };
      return Promise.reject(message);
    }
    return knex(this.tableName).insert(payload);
  }

  /**
   * Check if entry is in store.
   *
   * @method isInCache
   * @param {Object} property - pair
   * @return {Promise} entry if found, rejection if not
   * @example
   *  ```
   *   let subject = new Model("pet");
   *   subject.store({name: "Owly});
   *   subject.isInCache({name: "Owly})
   *     .then(result => console.log(result)); // return entry
   *  ```
   */
  isInCache(property) {
    if (!(property)) {
      let message =  {
        status: "error",
        message: "Model:isInCache property wrong"
      };
      return Promise.reject(message);
    }
    return knex(this.tableName).where(property)
      .then(result => result[0]);
  }

  /**
   * Destroy cache of current store.
   *
   * @return {Promise}
   */
  clearCache() {
    return knex(this.tableName).truncate();
  }
}
module.exports = Model;
